package cn.jbolt.core.util;

import cn.hutool.core.io.FileUtil;
import cn.jbolt.core.base.config.JBoltConfig;
import cn.jbolt.core.consts.JBoltConst;
import com.jfinal.core.JFinal;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;

public class JBoltUploadFileUtil {

    public static String getRealLocalPath(String url) {
        if (url == null || StrKit.isBlank(url.toString()) || url.startsWith(JBoltConst.HTTP_MHSP) || url.startsWith(JBoltConst.HTTPS_MHSP)) {
            return null;
        }
        if (FileUtil.isAbsolutePath(url)) {
            if (StrKit.notBlank(JBoltConfig.BASE_UPLOAD_PATH_PRE)) {
                if (FileUtil.normalize(url).indexOf(FileUtil.normalize(JBoltConfig.BASE_UPLOAD_PATH_PRE)) == -1) {
                    //如果绝对路径里不包含 pre地址 说明不是有效可操作上传路径
                    LogKit.warn("不是可以操作的上传路径：" + url);
                    return null;
                }
            } else {
                if (FileUtil.normalize(url).indexOf(FileUtil.normalize(PathKit.getWebRootPath() + "/" + JFinal.me().getConstants().getBaseUploadPath())) == -1) {
                    //如果绝对路径里不包含 webroot+upload 说明不是有效可操作上传路径
                    LogKit.warn("不是可以操作的上传路径：" + url);
                    return null;
                }
            }
            return url;
        }

        String urlValue = FileUtil.normalize(url.toString().trim());
        if (StrKit.isBlank(JBoltConfig.BASE_UPLOAD_PATH_PRE)) {
            return FileUtil.normalize(PathKit.getWebRootPath() + JBoltConst.SLASH_STR + urlValue);
        }
        String pre = FileUtil.normalize(JBoltConfig.BASE_UPLOAD_PATH_PRE);
        if (!urlValue.startsWith(pre)) {
            urlValue = FileUtil.normalize(pre + JBoltConst.SLASH_STR + urlValue);
        }
        return urlValue;
    }

    public static boolean delete(String url) {
        String filePath = getRealLocalPath(url);
        if (StrKit.isBlank(filePath)) {
            return false;
        }
        if(!FileUtil.isAbsolutePath(filePath)){
            return false;
        }
        if(!FileUtil.exist(filePath)){
            //已经执行过删除
            return true;
        }
        if(!FileUtil.isFile(filePath)){
            throw new RuntimeException("欲删除内容必须为文件类型："+filePath);
        }
        return FileUtil.del(filePath);
    }
}
